package com.company.project.utils;

import com.company.project.core.exception.BusinessException;
import com.company.project.core.support.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.io.InputStream;

/**
 * springmvc下载文件
 *
 * @author xuew
 * @date 2017/11/20
 */
public class DownloadFileUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(DownloadFileUtil.class);

    public static ResponseEntity<byte[]> createResponseEntity(InputStream is, String fileName){
        try {
            byte[] body = new byte[is.available()];
            is.read(body);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attchement;filename="+fileName+System.currentTimeMillis()+ "." + ExcelUtil.OFFICE_EXCEL_2010_POSTFIX);
            HttpStatus statusCode = HttpStatus.OK;
            return new ResponseEntity<>(body, headers, statusCode);
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.INTERNAL_SERVER_ERROR,"暂时无法生成",e.getCause().getCause());
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error("流关闭异常",e);
                }
            }
        }
    }
}
